{ "metadata": { "kernelspec": { "codemirror_mode": "scheme", "display_name": "Scheme", "language": "scheme", "name": "calico_scheme_kernel" }, "name": "", "signature": "sha256:fc9ff576f00fb3bedef5947d30d3e10fede5e78decf4bd2804f31f47e08a61e4" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "CS245 Programming Languages" ] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Douglas Blank" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Bryn Mawr College, Fall 2014" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "On the first exam, I asked you to write the function `list-of` that takes a function $f$, and returns a function that takes a list. The returned function should return `#t` if every item in the list has `(f item)` as `#t`.\n", "\n", "It would work like this:\n", "\n", "```scheme\n", "In [1]: ((list-of number?) '(1 2 3 4))\n", "Out [1]: #t\n", "```\n", "\n", "Here is one possible answer:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "(define list-of\n", " (lambda (f)\n", " (lambda (ls)\n", " (cond\n", " ((null? ls) #t)\n", " ((f (car ls)) ((list-of f) (cdr ls)))\n", " (else #f)))))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That is a simple implementation of the definition. But it does recreate the function that takes the list each time it needs it, because the function `(list-of f)` doesn't have a name. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is a version that uses `letrec` (let allowing recursive definitions), so that you only define that function once, and give it a name:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "(define list-of\n", " (lambda (f)\n", " (letrec ((list-of-f\n", " (lambda (ls)\n", " (cond\n", " ((null? ls) #t)\n", " ((not (f (car ls))) #f)\n", " (else (list-of-f (cdr ls)))))))\n", " list-of-f)))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "That version is a bit verbose, but also gets the job done.\n", "\n", "Finally, here is a version that uses the \"named let\" construct in Scheme:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "(define list-of\n", " (lambda (f)\n", " (lambda (ls)\n", " (let loop ((ls ls))\n", " (cond\n", " ((null? ls) #t)\n", " ((not (f (car ls))) #f)\n", " (else (loop (cdr ls))))))))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ah, yes. That is short, and beautiful. \n", "\n", "Which do you prefer? Do they all give the same answers? Are there pros and cons to each?" ] } ], "metadata": {} } ] }